<style>
.compositionDoc .color_top .el-input__inner {
  width: 160px;
  height: 30px;
}
.compositionDoc .color_top .el-input {
  width: 160px;
  height: 30px;
  /* margin-top: 14px; */
}
.el-icon-success,
.el-icon-delete {
  margin-right: 7px;
}
.compositionDoc .el-button + .el-button {
  margin-left: 0;
}
.compositionDoc .el-button {
  padding: 8px 15px;
  margin-right: 12px;
  height: 30px;
}
</style>

<style scoped>
.compositionDoc {
  margin-right: 15px;
  padding: 0 15px;
  background-color: white;
  height: 95vh;
  position: relative;
}

.color_top {
  display: flex;
  height: 60px;
  white-space: nowrap;
  border-bottom: 2px solid #f4f4f4;
  padding-top: 15px;
}
.color_w {
  padding: 3px 6px 0 0;
  /* color: #757575; */
}
.l {
  margin-left: 17px;
}
.color_button {
  margin: 15px 0;
  white-space: nowrap;
  display: flex;
}
.footView span {
  float: left;
  margin-right: 48px;
  line-height: 6vh;
  font-size: 14px;
}
.footView span i {
  margin-right: 5px;
}
</style>

<template>
  <!-- 成份建档 -->
  <div class="compositionDoc">
    <div class="color_top">
      <p class="color_w">成份编号</p>
      <el-input v-model="no" autofocus="autofocus" id="input"></el-input>
      <p class="color_w l">成份</p>
      <el-input v-model="name"></el-input>
      <p class="color_w l">繁体</p>
      <el-input v-model="traditionalName"></el-input>
      <p class="color_w l">英文</p>
      <el-input
        ref="inp4"
        v-model="englishName"
        @keyup.enter.native="preservation"
      ></el-input>
    </div>
    <!-- 按钮 -->
    <div class="color_button">
      <el-button
        style="z-index: 2"
        @click="preservation"
        type="primary"
        icon="el-icon-folder-checked"
        >保存</el-button
      >
      <!-- <el-button><i class="el-icon-download"></i>导入</el-button> -->
      <div class="dr">
        <i class="el-icon-download"></i>
        导入
        <input
          ref="upload"
          accept=".xls, .xlsx"
          class="outputlist_upload"
          type="file"
        />
      </div>
      <el-button @click="EXp" icon="el-icon-upload2">导出</el-button>
      <el-button @click="dele" icon="el-icon-delete">删除</el-button>
    </div>
    <!-- 表格 -->
    <el-table
      :data="tableData"
      id="outTable"
      style="width: 100%"
      height="74vh"
      highlight-current-row
      @row-click="rowClick"
      :header-cell-style="{ background: '#f4f4f4', padding: 0, height: '40px' }"
      :cell-style="{ padding: 0, height: '36px' }"
    >
      <el-table-column prop="no" label="成份编号" width="180">
      </el-table-column>
      <el-table-column prop="name" label="成份"> </el-table-column>
      <el-table-column prop="traditionalName" label="繁体"> </el-table-column>
      <el-table-column prop="englishName" label="英文"> </el-table-column>
    </el-table>

    <foot-view
      class="footView"
      :pagesNum="pagesNum"
      :hasPagination="true"
      :pageSize="limit"
      @handleSizeChange="handleSizeChange"
      @handleCurrentChange="handleCurrentChange"
    >
      <div slot="text">
        <span>数据库：{{ jxQuarter }}</span>
      </div>
    </foot-view>
  </div>
</template>

<script>
import {
  getComposition,
  postComposition,
  deleteComsition,
  putComposition,
  postExcelCom
} from '../../../network/composition'
import XLSX from 'xlsx'
import FileSaver from 'file-saver'
import footView from '../../../components/FootView'
import enterUp from '../../../components/mixins/enterUp'
import outex from '../../../components/mixins/outexp'
import { get } from '../../../network/customerOrderTotal'
export default {
  name: 'compositionDoc',
  mixins: [enterUp, outex],
  created() {
    let jxQuarterVal = document.cookie.match(RegExp('jxQuarter' + '=([^;]+)'))
    this.jxQuarter = jxQuarterVal ? jxQuarterVal[1] : null

    this.inpList = this.getInput()
    this._getComposition({ limit: this.limit, page: this.currentPage })
    // 总条数，总页码赋值
    getComposition().then((res) => {
      // console.log(res.data.data.length)
      this.dataLen = res.data.data.length
      this.pagesNum = Math.ceil(this.dataLen / this.limit)
    })
  },
  components: {
    footView
  },
  data() {
    return {
      inpList: [],
      // 总数据条数
      JList: [],
      outputs: [],
      dataLen: 0,
      // 总页码
      pagesNum: 0,
      // 分页条数
      limit: 20,
      // 当前页码
      currentPage: 1,
      tableData: [],
      value: '',
      no: '',
      id: '',
      name: '',
      traditionalName: '',
      englishName: '',
      aList: [],
      jxQuarter: null
      // jxQuarter: document.cookie.match(RegExp('jxQuarter'+'=([^;]+)'))[1],
    }
  },
  watch: {
    dataLen(a, b) {
      this.pagesNum = Math.ceil(this.dataLen / this.limit)
    }
  },
  methods: {
    EXp() {
      getComposition().then((res) => {
        this.tableData = res.data.data
        this.$nextTick(() => {
          this.exp()
          this._getComposition({ limit: this.limit, page: this.currentPage })
        })
      })
    },
    _getComposition(params = {}) {
      getComposition(params).then((res) => {
        // console.log(res)
        this.tableData = res.data.data.slice(
          (this.currentPage - 1) * this.limit,
          this.currentPage * this.limit
        )
        this.id = ''
        this.no = ''
        this.name = ''
        this.traditionalName = ''
        this.englishName = ''
        if (this.tableData.length == 0 && this.currentPage > 1) {
          this.currentPage--
          this._getArtNo({ limit: this.limit, page: this.currentPage })
        }
      })
    },
    preservation() {
      this.InpFocus()
      if (this.no == '' || this.name == '') {
        this.$message({
          type: 'warning',
          offset: 400,
          message: '成份编号和成份不能为空'
        })
        this.InpFocus()
        return
      }
      this.$refs.inp4.blur()
      var obj = {
        id: this.id,
        no: this.no,
        name: this.name,
        traditionalName: this.traditionalName,
        englishName: this.englishName
      }
      var obj1 = {
        no: this.no,
        name: this.name,
        traditionalName: this.traditionalName,
        englishName: this.englishName
      }

      for (const i of this.tableData) {
        if (i.no == this.no) {
          this.$confirm('是否修改此成份编号的数据, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          })
            .then(() => {
              putComposition(obj).then((res) => {
                console.log(res.data)
                if (res.data.code == 200) {
                  this._getComposition({
                    limit: this.limit,
                    page: this.currentPage
                  })
                  this.$message({
                    type: 'success',
                    offset: 400,
                    message: '修改成功!'
                  })
                } else {
                  this.$message.error({
                    offset: 400,
                    message: '修改失败!'
                  })
                }
              })
            })
            .catch(() => {
              this.$message({
                type: 'info',
                offset: 400,
                message: '已取消修改'
              })
            })
          return
        }
      }
      console.log(obj1)
      postComposition(obj1).then((res) => {
        console.log(res.data)
        if (res.data.code == 200) {
          this.dataLen++
          this.$message({
            type: 'success',
            offset: 400,
            message: '添加成功!'
          })
          this.InpFocus()
          this._getComposition({ limit: this.limit, page: this.currentPage })
        } else if (res.data.code !== 200) {
          this.$message.error({
            offset: 400,
            message: '修改失败'
          })
        }
      })
    },
    InpFocus() {
      var pFocus = document.getElementById('input')
      pFocus.focus()
      pFocus.select()
    },

    dele() {
      if (this.id == '') {
        this.$message({
          type: 'warning',
          offset: 400,
          message: '请选择要删除的数据!'
        })
        return
      }
      let obj = { id: this.id }
      this.$confirm('是否删除此成份编号的数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          deleteComsition(obj).then((res) => {
            console.log(res.data)
            if (res.data.code == 200) {
              this.dataLen--
              this._getComposition({
                limit: this.limit,
                page: this.currentPage
              })
              this.$message({
                type: 'success',
                offset: 400,
                message: '删除成功!'
              })
            } else if (res.data.code == 204) {
              this.$message.error({
                message: '该数据有关联数据, 删除失败!'
              })
            } else {
              this.$message.error({
                message: '删除失败!'
              })
            }
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            offset: 400,
            message: '已取消删除'
          })
        })
    },

    rowClick(e) {
      this.id = e.id
      this.no = e.no
      this.name = e.name
      this.traditionalName = e.traditionalName
      this.englishName = e.englishName
    },

    readExcel(e) {
      console.log(111)
      //表格导入
      var that = this
      const files = e.target.files
      console.log(files)
      if (files.length <= 0) {
        //如果没有文件名
        return false
      } else if (!/\.(xls|xlsx)$/.test(files[0].name.toLowerCase())) {
        this.$Message.error('上传格式不正确，请上传xls或者xlsx格式')
        return false
      }

      const fileReader = new FileReader()
      fileReader.onload = (ev) => {
        try {
          const data = ev.target.result
          const workbook = XLSX.read(data, {
            type: 'binary'
          })
          const wsname = workbook.SheetNames[0] //取第一张表
          const ws = XLSX.utils.sheet_to_json(workbook.Sheets[wsname]) //生成json表格内容
          console.log(ws)
          for (var a = 0; a < ws.length; a++) {
            this.JList.push(JSON.stringify(ws[a]))
          }
          console.log(this.JList)
          // let obj = {paramsList:ac,fieldMap:{brandedCompany:"123456"}}
          let obj = {
            paramsList: this.JList,
            fieldMap: { brandedCompany: this.brandedCompany }
          }
          console.log({ obj })
          postExcelCom(obj).then((res) => {
            console.log(res.data)
            if (res.data.code == 200) {
              this.$message({
                type: 'success',
                offset: 400,
                message: '导入成功!'
              })
              this._getComposition({
                limit: this.limit,
                page: this.currentPage
              }) //重新请求页面数据
            } else {
              this.$message({
                type: 'info',
                offset: 400,
                message: '导入失败，成份编号或成份重复!'
              })
            }
          })

          that.outputs = [] //清空接收数据
          //编辑数据
          for (var i = 0; i < ws.length; i++) {
            var sheetData = {
              address: ws[i].addr,
              value: ws[i].value
            }
            that.outputs.push(sheetData)
          }
          this.$refs.upload.value = ''
        } catch (e) {
          return false
        }
      }
      fileReader.readAsBinaryString(files[0])
    },

    // 每页显示页数改变
    handleSizeChange(val) {
      this.limit = val
      // 总页码赋值
      this.pagesNum = Math.ceil(this.dataLen / this.limit)
      this._getComposition({ limit: this.limit, page: this.currentPage })
    },
    // 当前页改变
    handleCurrentChange(val) {
      this.currentPage = val
      this._getComposition({ limit: this.limit, page: this.currentPage })
    }
  },
  mounted() {
    this.$refs.upload.addEventListener('change', (e) => {
      //绑定监听表格导入事件
      this.readExcel(e)
    })
  }
}
</script>
